package com.hoyue.dao.impl;

import com.hoyue.dao.PageDao;
import com.hoyue.utils.C3P0Utils;
import com.hoyue.utils.GenericsUtils;
import com.hoyue.utils.Page;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Hoyue_network1
 * @version 1.0
 * Creat by 2018/8/30 11:38
 */
public class PageDaoImpl<T> implements PageDao<T>{
	QueryRunner qr = C3P0Utils.getQueryRunner();

	private Class<T> clazz;

	public PageDaoImpl() {
		clazz = GenericsUtils.getSuperGenericType(getClass());
	}

	@Override
	public Page<T> getListByPage(int page, String tableName) throws SQLException {
		Page<T> pb = new Page<>(page);

		// 安排总记录数
		long totalItem = (long)qr.query("select count(*) from " + tableName, new ScalarHandler());
		pb.setTotalItem(totalItem);

		// 安排总页数
		int totalPage = (int)(totalItem % pb.getPageSize() == 0 ? totalItem / pb.getPageSize() : totalItem / pb.getPageSize() + 1);
		pb.setTotalPage(totalPage);

		String sql = "select * from " + tableName + " order by id limit ?,?";

		int start = (page - 1) * pb.getPageSize();
		List<T> Generic = qr.query(sql,new BeanListHandler<>(clazz),start,pb.getPageSize());

		pb.setList(Generic);

		return pb;
	}
}
